﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.DirectoryServices;

namespace Hvam.SharePoint.Features.IIS {
    public class IISManagementUpdaterJob : SPJobDefinition {
        public IISManagementUpdaterJob() { }

        public IISManagementUpdaterJob(SPService service) : this(PreferredName, service) {
        }

        public IISManagementUpdaterJob(string name, SPService service)
            : base(name, service, null, SPJobLockType.None) {
        }

        public override void Execute(Guid targetInstanceId) {
            foreach (var webApplication in SPWebService.ContentService.WebApplications) {
                foreach (var v in webApplication.IisSettings) {
                    var instanceId = v.Value.PreferredInstanceId;

                    var iisWebSite = new SPIisWebSite(instanceId);

                    var webSiteEntry = new DirectoryEntry("IIS://" + Environment.MachineName + "/W3SVC/" + instanceId + "/Root");
                    var applicationPoolEntry = new DirectoryEntry("IIS://" + Environment.MachineName + "/W3SVC/AppPools/" + webSiteEntry.Properties["AppPoolId"][0]);
                    var state = applicationPoolEntry.InvokeGet("AppPoolState").ToString();
                    var aplicationPoolState = (ApplicationPoolState)Enum.Parse(typeof(ApplicationPoolState), state);

                    IISManagementService.Local.UpdateState(webApplication, v.Key, iisWebSite.ServerState, aplicationPoolState);
                }
            }
        }

        // Properties
        public static string PreferredName {
            get {
                return "IIS Management Updater";
            }
        }
        
        public static SPSchedule PreferredSchedule {
            get {
                return SPSchedule.FromString("every 15 minutes");
            }
        }

        public static string PreferredTitle {
            get {
                return "IIS Management Updater";
            }
        }
    }
}
